package com.example.security.demo.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.security.demo.entity.SysMenu;
import com.example.security.demo.entity.SysUser;
import com.example.security.demo.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhanpengguo
 * @date 2019-10-08 10:32
 */
@Slf4j
@RestController
@AllArgsConstructor
public class HelloController {

    private final SysUserMapper sysUserMapper;

    @GetMapping("/hello")
    public String hello() {
        List<SysMenu> mapList = sysUserMapper.selectMenuByUsername("admin");
        log.info("sysMenus:{}", JSONUtil.toJsonStr(mapList));
        Set<SimpleGrantedAuthority> collect = mapList.stream().map(sysMenu -> new SimpleGrantedAuthority(sysMenu.getPerms())).collect(Collectors.toSet());
        log.info("获取权限：{}", JSONObject.toJSONString(collect));
        return "hello,world";
    }

    @PreAuthorize("hasAuthority('sys:user:delete')")
    @DeleteMapping("/delete")
    public String delete() {
        return "删除成功";
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @PutMapping("/update")
    public String update() {
        return "修改成功";
    }
}
